package com.batchengine.action;

import static com.batchengine.Constants.EMPTY_STRING;
import com.batchengine.Definitions;
import static com.batchengine.Definitions.ContextParams.TASK_CLASS;
import static com.batchengine.Definitions.TaskType.PYTHON;
import com.batchengine.task.TaskContext;
import static com.batchengine.util.EnvUtil.getBaseFolderLocation;
import com.batchengine.util.LoggingFactory;
import static com.batchengine.util.Util.createSpaceString;
import org.apache.log4j.Logger;

import java.io.InputStreamReader;
import static java.lang.Runtime.getRuntime;
import static java.lang.String.format;
import static java.lang.System.setProperty;

/**
 * User: sunil.incubator@yahoo.com
 * Date: Sep 18, 2009
 * Time: 12:01:25 AM
 */
public class PythonAction implements Action {

    private static final Logger logger = LoggingFactory.createLogger();

    @Override
    public Object execute(TaskContext context) {


        StringBuilder result = new StringBuilder();
        try {

            String fileName = (String) context.getContextParam(TASK_CLASS);
            String[] arguments = (String[]) context.getContextParam(Definitions.ContextParams.ARGUMENTS);
            String spaceSeperatedString = createSpaceString(arguments);
            Process myProcess = getRuntime().exec(format("python %s %s", fileName, (null == spaceSeperatedString ? EMPTY_STRING : spaceSeperatedString)));
            InputStreamReader myIStreamReader = new InputStreamReader(myProcess.getInputStream());
            int ch;
            while ((ch = myIStreamReader.read()) != -1) {
                result.append((char) ch);
            }
            logger.debug("python task executed " + result);
            //TODO
//            Thread.sleep(5000 * 3);
        } catch (Exception e) {
            logger.error("error@PythonAction#execute");
            return null;
        }
        return result;
    }

    @Override
    public Definitions.TaskType getType() {
        return PYTHON;
    }

    public static void main(String[] args) {

//        setProperty("conf.file", "/host//codebase/bashengine/settings/conf/be.properties");
//        setProperty("conf.file", "D:/mkhoj/codebase/bashengine_google/src/main/resources/conf/be.properties");
        TaskContext context = TaskContext.createTaskContext(1l);
//        context.addcontextParam(TASK_CLASS, String.format("%s /host//codebase/bashengine/src/com//bashengine/test/helloworld.py", getBaseFolderLocation()));
        context.addcontextParam(TASK_CLASS, String.format("%s D://codebase/bashengine/src/com//bashengine/test/helloworld.py", getBaseFolderLocation()));

        Action action = new PythonAction();
        Object o = action.execute(context);
        System.out.println(o);
    }
}
